package com.lianboke.link.ad.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.TextView;

import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.dbmanager.OrderDetailsCacheUtils;
import com.lianboke.link.ad.updateUtils.AppUtils;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时任务的服务
 * Created by admin on 2018/1/22.
 */

public class TimerOrderService extends Service {
    public static final String TIMER_ORDER_SERVICE_ACTION_START = "com.lianboke.link.ad.services.timeroder.action.start";
    public static final String TIMER_ORDER_SERVICE_ACTION_STOP = "com.lianboke.link.ad.services.timeroder.action.stop";


    private Timer timerOrders ;
    private TimerTask timerTaskOrders;

    private List<String> appNameDatas = new ArrayList<String>();
    private int index = -1;//顺序
    private int appNameSize = 0;//数量

    private OrderDetailsCacheUtils orderDetailsCacheUtils ;
    private Context mContext;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getBaseContext();
        if(mContext==null){
            mContext = getApplicationContext();
        }
        orderDetailsCacheUtils = new OrderDetailsCacheUtils(mContext);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent!=null && !TextUtils.isEmpty(intent.getAction())){
            if(TIMER_ORDER_SERVICE_ACTION_START.equals(intent.getAction())){
                //开始
                KLog.e("------------------onStartCommand---------------------:"+intent.getAction());
                appNameDatas = intent.getStringArrayListExtra("data");
                appNameSize = appNameDatas.size();
                startTimerOrder();
            }else if(TIMER_ORDER_SERVICE_ACTION_STOP.equals(intent.getAction())){
                //结束
                KLog.e("------------------onStartCommand---------------------:"+intent.getAction());
                stopTimerOrderService();
            }
        }
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destoryTimeTaskUpdateParams();
    }

    /**
     * 开始任务定时
     */
    private void startTimerOrder(){
        initTimerOrderParams();
    }
    /**
     * 结束任务
     */
    private void stopTimerOrderService(){
        destoryTimeTaskUpdateParams();
        stopSelf();
    }

    /**
     * 结束全部启动任务
     */
    private void sendFinishTimerOrder(){
        Intent stopIntent = new Intent();
        stopIntent.setAction(CommonParams.TimerParams.TIMER_ORDER_STOP_ACTION);
        sendBroadcast(stopIntent);
    }
    /**
     * 初始化定时参数
     */
    public void initTimerOrderParams(){
        timerTaskOrders = new TimerTask() {
            @Override
            public void run() {
                //定时启动任务
                starAppByAppName();
            }
        };
        if(timerOrders==null){
            timerOrders =new Timer();
        }
        timerOrders.schedule(timerTaskOrders,CommonParams.TimerParams.TIMER_ORDER_DELAY_TIME,CommonParams.TimerParams.TIMER_ORDER_PERIOD_TIME);
    }

    /**
     * 启动只当app
     */
    private void starAppByAppName(){
        KLog.e("------------------starAppByAppName---------------------:"+index);
        ++index;
        if(index>=appNameSize){
            //全部执行完毕
            sendFinishTimerOrder();
            return;
        }
        String strAppPackageName = appNameDatas.get(index);
        if(AppUtils.hasApp(this,appNameDatas.get(index))){
            KLog.e("service_log","--------AppUtils.hasApp--------true------");
            //上报任务操作信息
            long orderId = orderDetailsCacheUtils.queryOrderTypeIdByAppName(strAppPackageName);
            if(orderId!=-1){
                reportedAppInfo(3,String.valueOf(orderId),strAppPackageName);
            }
            //更新任务的启动时间
            orderDetailsCacheUtils.updateOrderTypeLastTimeByAppName(strAppPackageName, DateUtil.getCurDateStr("yyyy-MM-dd"));
            //启动指定任务
            DeviceUtils.doStartApplicationWithPackageName(mContext,strAppPackageName);
        }else{
            //未安装，直接过滤掉
            KLog.e("service_log","--------AppUtils.hasApp--------false------");
        }
    }


    /**
     * 销毁定时检测更新服务
     */
    public void destoryTimeTaskUpdateParams(){
        try{
            if(timerTaskOrders!=null){
                timerTaskOrders.cancel();
            }
        }catch (Exception e){

        }finally {
            timerTaskOrders = null;
        }
        try{
            if(timerOrders!=null){
                timerOrders.cancel();
            }
        }catch (Exception e){

        }finally {
            timerOrders = null;
        }
        if(appNameDatas!=null){
            appNameDatas.clear();
        }
    }
    /**
     * 上报任务状态 1 安装、2 卸载、3 启动、4 完成
     * @param status
     * @param packagename (卸载时需要传卸载的packname)
     */
    public void  reportedAppInfo(int status,String orderId,String packagename){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(this.getBaseContext()));
        params.put("version",DeviceUtils.getVersionName(this.getBaseContext()));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);
        params.put("taskid",orderId);
        params.put("appname",packagename);
        params.put("status",String.valueOf(status));
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_REPORTPROCESS, params, new HttpCallBack<Integer>() {
            @Override
            public void onSuccess(Integer data) {
                if(data!=null && data.intValue()==1){
                    KLog.e("shangbao_log","-------------onSuccess-------------------");
                }
            }
            @Override
            public void onFail(String msg) {
                KLog.e("shangbao_log","-------------onFail-------------------"+msg);
            }
        });
    }

}
